package crawlers;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

public class WebpagetestCrawler {
	public static String getDomainId(String domain) {
		String id = "";
		
		try {
			//Goto homepage
			String url = "http://www.webpagetest.org/";
			Connection conn = Jsoup.connect(url);
			Document doc = conn
							.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
							.header("accept-Language", "en-us,en;q=0.5")
							.header("referer", "http://www.webpagetest.org/")
							.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
							.get();
			Response response = conn.response();
			String vh = doc.select("input[name=vh]").get(0).attr("value");
			String vo = doc.select("input[name=vo]").get(0).attr("value");
			String vd = doc.select("input[name=vd]").get(0).attr("value");
			
			try {
				Thread.sleep(5000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			url = "http://www.webpagetest.org/runtest.php";
			conn = Jsoup.connect(url);
			
			//Goto runtest.php
			 doc = conn
							.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
							.header("accept-Language", "en-us,en;q=0.5")
							.header("host", "www.webpagetest.org")
							.header("referer", "http://www.webpagetest.org/")
							.cookie("o",response.cookie("o"))
							.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
							.data("url", domain)
							.data("vh",vh)
							.data("vo", vo)
							.data("vd", vd)
							.data("where", "Dulles_VA")
							.data("browser", "IE8")
							.data("location", "Dulles_IE8.DSL")
							.data("bwDown", "1500")
							.data("bwUp", "384")
							.data("latency", "")
							.followRedirects(false)
							.post();
			
			try {
				Thread.sleep(5000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
			response = conn.response();
			
			if (response.header("Location")!= null && !response.header("Location").isEmpty()) {
				String[] splitString = response.header("Location").split("/", 6);
				id = splitString[4];
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return id;
			
	}
}
